<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/goods' }">商品列表</el-breadcrumb-item>
        <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
       <el-alert
         title="添加商品信息"
         type="info" show-icon :closable="false" center>
        </el-alert>
        <!-- 步骤条 -->
        <el-steps :active="activeIndex-0" finish-status="success" align-center>
          <el-step title="基本信息"></el-step>
          <el-step title="商品参数"></el-step>
          <el-step title="商品属性"></el-step>
          <el-step title="商品图片"></el-step>
          <el-step title="商品内容"></el-step>
          <el-step title="完成"></el-step>
        </el-steps>
        <!-- tabs栏  标签页-->
    <el-form :model="AddForm" :rules="AddFormrules" ref="ruleFormRef" label-position="top">
        <el-tabs @tab-click="tabClicked" tab-position="left" v-model="activeIndex" :before-leave="beforeTabLeave">
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
                <el-input v-model="AddForm.goods_name"/>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
                <el-input v-model="AddForm.goods_price"/>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
                <el-input v-model="AddForm.goods_weight"/>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number" type="number">
                <el-input v-model="AddForm.goods_number"/>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_number">
                <el-cascader
                v-model="AddForm.goods_cat"
                :options="GoodCates"
                :props="PropsgoodsList"
                @change="cascaderhandleChange" size="mini"></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item :label="item.attr_name" v-for="item in manyData" :key="item.attr_id">
             <el-checkbox-group v-model="item.attr_vals">
               <el-checkbox v-for="(item1, index) in item.attr_vals" :key="index" :label="item1" border></el-checkbox>
             </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="(item, index) in onlyData" :key="index">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
            :action="uploadURL"
            :on-remove="handleRemove" list-type="picture"
            :on-preview="handlePreview" :headers="headerObj"
            :on-success="handleSuccess">
              <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="cotent">
            </quill-editor>
            <el-button @click="addGoods" type="primary" style="margin-top: 10px">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
    </el-form>
    </el-card>
    <el-dialog
     :visible.sync="ImgdialogVisible"
     width="50%">
     <img :src="Prviewimg" alt="" style="width: 100%">
</el-dialog>
  </div>
</template>

<script>
import { cloneDeep } from 'lodash'
export default {
  data () {
    return {
      activeIndex: '0',
      GoodCates: [],
      PropsgoodsList: {
        //  保存的id
        value: 'cat_id',
        //  渲染的内容
        label: 'cat_name',
        expandTrigger: 'hover'
      },
      //  表单添加的数据
      AddForm: {
        goods_name: '',
        goods_price: '',
        goods_weight: '',
        goods_number: '',
        //  记录级联选择器的数据通过表单一起上传
        goods_cat: [],
        pics: [],
        goods_introduce: ''
      },
      //  表单验证数据
      AddFormrules: {
        goods_name: [{ required: true, message: '请输入商品名称', trigger: 'blur' },
          { min: 3, max: 8, message: '3~8个字符' }],
        goods_price: [{ required: true, message: '请输入商品价格', trigger: 'blur' },
          { min: 2, max: 8, message: '3~8个字符' }],
        goods_weight: [{ required: true, message: '请输入商品重量', trigger: 'blur' },
          { min: 3, max: 8, message: '3~8个字符' }],
        goods_number: [{ required: true, message: '请输入商品数量', trigger: 'blur' }]
      },
      manyData: [],
      //  属性参数
      onlyData: [],
      uploadURL: 'http://115.159.87.220:8888/api/private/v1/upload',
      //  上传图片的请求头
      headerObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      ImgdialogVisible: false,
      Prviewimg: '',
      //  富文本编辑器的数据绑定
      cotent: ''
    }
  },

  created () {
    this.getGoodsCate()
  },
  computed: {},
  methods: {
    async getGoodsCate () {
      const { data: res } = await this.axios.get('categories')
      if (res.meta.status !== 200) return this.$message.error('获取数据失败')
      this.GoodCates = res.data
    },
    cascaderhandleChange () {
    //   console.log(this.AddForm.goods_cat)
      if (this.AddForm.goods_cat.length !== 3) {
        this.AddForm.goods_cat = []
      }
      return true
    },
    //  如果没有选择商品分类 tab标签就不允许跳转
    beforeTabLeave (activeName, oldActiveName) {
    //   console.log('离开' + oldActiveName)
    //   console.log('进入' + activeName)
      if (oldActiveName === '0' && this.AddForm.goods_cat.length !== 3) {
        this.$message.error('请先选择商品分类')
        return false
      }
    },
    async tabClicked () {
      const id = this.AddForm.goods_cat[2]
      if (this.activeIndex === '1') {
        // console.log(this.activeIndex)
        const { data: res } = await this.axios.get(`categories/${id}/attributes`, {
          params: {
            sel: 'many'
          }
        })
        if (res.meta.status !== 200) return this.$message.error('获取数据失败')
        res.data.forEach(item => {
          //  需要判断空字符串需要转变为空数组
          item.attr_vals = item.attr_vals === '' ? [] : item.attr_vals.split(' ')
        })
        this.manyData = res.data
        // console.log(res)
      } else if (this.activeIndex === '2') {
        const { data: res } = await this.axios.get(`categories/${id}/attributes`, {
          params: {
            sel: 'only'
          }
        })
        if (res.meta.status !== 200) return this.$message.error('获取数据失败')
        this.onlyData = res.data
      }
    },
    //  图片上传成功 将图片保存到表单数据中
    handleSuccess (response) {
      // response.data.tmp_path
      this.AddForm.pics.push({ pic: response.data.tmp_path })
    },
    //  删除图片
    handleRemove (file) {
      //  返回索引号 进行数组删除
      const i = this.AddForm.pics.findIndex(x => x.pic === file.response.data.tmp_path)
      this.AddForm.pics.splice(i, 1)
      // console.log(this.AddForm)
    },
    handlePreview (file) {
      this.ImgdialogVisible = true
      this.Prviewimg = 'http://115.159.87.220:8888/' + file.response.data.tmp_path
    },
    //  添加商品的事件
    addGoods () {
      this.$refs.ruleFormRef.validate(async (flag) => {
        if (!flag) return this.$message.error('请填写表单!')
        const Formdata = cloneDeep(this.AddForm)
        Formdata.goods_cat = Formdata.goods_cat.join(',')
        Formdata.attrs = []
        this.manyData.forEach(item => {
          Formdata.attrs.push({
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(' ')
          })
        })
        this.onlyData.forEach(item => {
          Formdata.attrs.push({
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          })
        })
        const { data: res } = await this.axios.post('goods', Formdata)
        if (res.meta.status !== 201) return this.$message.error('添加商品失败')
        this.$message.success('创建成功')
        this.$router.go(-1)
      })
    }
  }
}
</script>

<style scoped lang='less'>
.el-steps {
  margin: 15px 0;
}
.el-checkbox {
  margin-right: 0px;
}
</style>
